package com.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.domain.Issue;
import com.domain.UserLikeWithIssue;
import com.mapper.helping.UserLikeWithIssueMapper;
import com.service.IIssueService;
import com.service.IUserLikeWithIssueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.util.HotUtil;
import com.util.UserUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.HashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 大忽悠
 * @since 2022年02月08日
 */
@RequiredArgsConstructor
@Service
public class UserLikeWithIssueServiceImpl extends ServiceImpl<UserLikeWithIssueMapper, UserLikeWithIssue> implements IUserLikeWithIssueService {
   private final IIssueService iIssueService;
   private final HotUtil hotUtil;
    /**
     * 0.不能重复对一个问题进行点赞操作
     * 1.映射表插入一条记录
     * 2.对应问题的点赞总数加一
     * 问题对应的热度加5
     */
    @Override
    @Transactional(transactionManager = "primaryTransactionManager")
    public Boolean likeTargetIssue(Integer issue_id) {
        //问题必须先存在
        Issue byId = iIssueService.getById(issue_id);
        Assert.isTrue(byId!=null&&byId.getIsDeleted()==0,"问题不存在");
        //判断是否已经点赞过了
        UserLikeWithIssue user = getOne(new QueryWrapper<UserLikeWithIssue>()
                .eq("issue_id", issue_id).eq("user_id", UserUtil.getUserId()));
        Assert.isNull(user,"请勿重复点赞");
        //映射表插入一条记录
        boolean save = save(UserLikeWithIssue.builder().issueId(issue_id).userId(UserUtil.getUserId()).build());
        //点赞数加一
        //boolean  save1= iIssueService.likeAdd(issue_id,1);
        byId.setLikeSum(byId.getLikeSum()+1);
        //问题热度加5
        byId.setHot(byId.getHot()+hotUtil.getISSUE_LIKE_HOT_ADD());
        boolean save1 = iIssueService.updateById(byId);
        return save&&save1;
    }

    /**
     * 1.映射表删除点赞记录
     * 2.对应问题的点赞总数减去一
     */
    @Override
    @Transactional(transactionManager = "primaryTransactionManager")
    public Boolean unLikeTargetIssue(Integer issue_id) {
        //问题必须先存在
        Issue byId = iIssueService.getById(issue_id);
        Assert.isTrue(byId!=null&&byId.getIsDeleted()==0,"问题不存在");
        //判断是否已经点赞过了
        UserLikeWithIssue user = getOne(new QueryWrapper<UserLikeWithIssue>()
                .eq("issue_id", issue_id).eq("user_id", UserUtil.getUserId()));
        Assert.notNull(user,"请先点赞");
        //映射表删除一条记录
        HashMap<String,Object> example = new HashMap<>();
        example.put("issue_id",issue_id);
        example.put("user_id",UserUtil.getUserId());
        boolean save = removeByMap(example);
        //点赞数减去一
        boolean  save1= iIssueService.likeAdd(issue_id,-1);
        return save && save1;
    }
}
